# -*- coding: utf-8 -*-

import logging
import os

from onlinebrary.lib.aggregator.lib_ru import LibRuAggregator
from onlinebrary.lib.aggregator.new_fictionbook_ru import NewFictionbookRuAggregator
from onlinebrary.lib.aggregator.aldebaran_ru import AldebaranRuAggregator

import thread

from pylons import g

log = logging.getLogger(__name__)

class AggregatorMaster(object):

    def __init__(self):
        self.aggregators_pool = [
                LibRuAggregator(),
                NewFictionbookRuAggregator(),
                AldebaranRuAggregator()
                ]
    
    def get_info(self, query):

        blocks_lock = thread.allocate_lock()
        blocks = dict()

        for aggregator in self.aggregators_pool:
            thread.start_new_thread(self.one_source_processor, (aggregator, query, blocks, blocks_lock))

        while len(blocks) < len(self.aggregators_pool): pass
        return blocks.values()
    
    def one_source_processor(self, aggregator, book_title, blocks, blocks_lock):
        if len(book_title) <= 4:
            return Exception("Запрос слишком маленький, меньше 4 символов :(")
            
        founded = aggregator.search_by_title(book_title)
        blocks_lock.acquire()
        blocks[aggregator.name] = founded
        blocks_lock.release()
    
    
